import React, { useState } from 'react'

interface APIConfigModalProps {
  isOpen: boolean
  onClose: () => void
  onSuccess: (provider: string, apiKey: string) => void
}

interface TestResult {
  success: boolean
  message: string
}

export const APIConfigModal: React.FC<APIConfigModalProps> = ({
  isOpen,
  onClose,
  onSuccess
}) => {
  const [provider, setProvider] = useState<'groq' | 'openai'>('groq')
  const [apiKey, setApiKey] = useState('')
  const [showKey, setShowKey] = useState(false)
  const [testing, setTesting] = useState(false)
  const [testResult, setTestResult] = useState<TestResult | null>(null)

  // 提供商配置
  const providerConfig = {
    groq: {
      name: 'Groq',
      icon: '🚀',
      description: '完全免费，响应极快',
      getKeyUrl: 'https://console.groq.com',
      recommended: true
    },
    openai: {
      name: 'OpenAI',
      icon: '🧠',
      description: 'GPT-3.5/GPT-4（需付费）',
      getKeyUrl: 'https://platform.openai.com',
      recommended: false
    }
  }

  // 重置表单
  const resetForm = () => {
    setApiKey('')
    setTestResult(null)
    setProvider('groq')
    setShowKey(false)
    setTesting(false)
  }

  // 关闭弹窗
  const handleClose = () => {
    resetForm()
    onClose()
  }

  // 测试API配置
  const testAPIConfig = async () => {
    if (!apiKey.trim()) {
      setTestResult({
        success: false,
        message: '请输入API密钥'
      })
      return
    }

    setTesting(true)
    setTestResult(null)

    try {
      // 发送测试请求到后端
      const response = await fetch('/api/ai/test-config', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          provider,
          api_key: apiKey.trim()
        })
      })

      const result = await response.json()

      if (result.success) {
        setTestResult({
          success: true,
          message: '连接成功！API密钥有效'
        })
      } else {
        setTestResult({
          success: false,
          message: result.message || 'API密钥无效或连接失败'
        })
      }
    } catch (error) {
      setTestResult({
        success: false,
        message: '连接失败，请检查网络或稍后重试'
      })
    } finally {
      setTesting(false)
    }
  }

  // 保存配置
  const saveConfig = async () => {
    if (!testResult?.success) {
      await testAPIConfig()
      return
    }

    try {
      // 发送配置到后端
      const response = await fetch('/api/ai/configure', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          provider,
          api_key: apiKey.trim()
        })
      })

      const result = await response.json()

      if (result.success) {
        onSuccess(provider, apiKey.trim())
        handleClose()
      } else {
        setTestResult({
          success: false,
          message: result.message || '配置保存失败'
        })
      }
    } catch (error) {
      setTestResult({
        success: false,
        message: '保存失败，请稍后重试'
      })
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div 
        className="bg-white rounded-xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto"
        style={{
          borderRadius: 'var(--radius-xl)',
          boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)'
        }}
      >
        {/* 弹窗头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">
            配置API密钥
          </h2>
          <button
            onClick={handleClose}
            className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 transition-colors text-gray-500 hover:text-gray-700"
          >
            ✕
          </button>
        </div>

        {/* 弹窗内容 */}
        <div className="p-6">
          {/* 提供商选择 */}
          <div className="mb-6">
            <h3 className="font-medium text-gray-900 mb-3">选择API提供商</h3>
            <div className="space-y-3">
              {Object.entries(providerConfig).map(([key, config]) => (
                <label
                  key={key}
                  className={`relative flex items-start p-4 rounded-lg border-2 cursor-pointer transition-all ${
                    provider === key 
                      ? 'border-blue-500 bg-blue-50' 
                      : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                  } ${config.recommended ? 'ring-2 ring-green-200' : ''}`}
                  style={{ borderRadius: 'var(--radius-lg)' }}
                >
                  <input
                    type="radio"
                    name="provider"
                    value={key}
                    checked={provider === key}
                    onChange={(e) => setProvider(e.target.value as 'groq' | 'openai')}
                    className="sr-only"
                  />
                  
                  {/* 推荐标签 */}
                  {config.recommended && (
                    <div className="absolute -top-2 -right-2 px-2 py-1 bg-green-500 text-white text-xs rounded-full">
                      推荐
                    </div>
                  )}
                  
                  <div className="flex-1">
                    <div className="flex items-center gap-3">
                      <span className="text-2xl">{config.icon}</span>
                      <div>
                        <h4 className="font-semibold text-gray-900">
                          {config.name}
                        </h4>
                        <p className="text-sm text-gray-600 mt-1">
                          {config.description}
                        </p>
                        <a 
                          href={config.getKeyUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-700 text-sm mt-2 hover:underline"
                          onClick={(e) => e.stopPropagation()}
                        >
                          获取API密钥 →
                        </a>
                      </div>
                    </div>
                  </div>
                  
                  {/* 选中指示器 */}
                  {provider === key && (
                    <div className="text-blue-600 ml-3">
                      <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                      </svg>
                    </div>
                  )}
                </label>
              ))}
            </div>
          </div>

          {/* API密钥输入 */}
          <div className="mb-6">
            <label className="block font-medium text-gray-900 mb-2">
              API密钥
            </label>
            <div className="relative">
              <input
                type={showKey ? 'text' : 'password'}
                value={apiKey}
                onChange={(e) => {
                  setApiKey(e.target.value)
                  setTestResult(null) // 清除之前的测试结果
                }}
                placeholder="粘贴您的API密钥"
                className="w-full px-4 py-3 pr-20 border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:outline-none transition-colors"
                style={{ borderRadius: 'var(--radius-lg)' }}
              />
              <button
                type="button"
                onClick={() => setShowKey(!showKey)}
                className="absolute right-3 top-1/2 -translate-y-1/2 px-3 py-1 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded transition-colors"
              >
                {showKey ? '隐藏' : '显示'}
              </button>
            </div>
            <p className="text-xs text-gray-500 mt-2 flex items-start gap-1">
              <span>🔒</span>
              <span>密钥将安全存储在本地，不会上传到服务器</span>
            </p>
          </div>

          {/* 测试结果 */}
          {testResult && (
            <div className={`mb-6 p-4 rounded-lg border-2 ${
              testResult.success 
                ? 'border-green-200 bg-green-50' 
                : 'border-red-200 bg-red-50'
            }`} style={{ borderRadius: 'var(--radius-lg)' }}>
              <div className="flex items-start gap-3">
                <div className={`flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center ${
                  testResult.success ? 'bg-green-500' : 'bg-red-500'
                }`}>
                  <span className="text-white text-sm">
                    {testResult.success ? '✓' : '✕'}
                  </span>
                </div>
                <div className="flex-1">
                  <p className={`font-medium ${
                    testResult.success ? 'text-green-800' : 'text-red-800'
                  }`}>
                    {testResult.success ? '连接成功' : '连接失败'}
                  </p>
                  <p className={`text-sm mt-1 ${
                    testResult.success ? 'text-green-700' : 'text-red-700'
                  }`}>
                    {testResult.message}
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* 操作按钮 */}
          <div className="flex gap-3">
            <button
              onClick={handleClose}
              className="flex-1 px-4 py-3 border-2 border-gray-200 rounded-lg hover:bg-gray-50 transition-colors font-medium"
              style={{ borderRadius: 'var(--radius-lg)' }}
            >
              取消
            </button>
            
            {!testResult?.success ? (
              <button
                onClick={testAPIConfig}
                disabled={!apiKey.trim() || testing}
                className="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium flex items-center justify-center gap-2"
                style={{ borderRadius: 'var(--radius-lg)' }}
              >
                {testing ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                    <span>测试中...</span>
                  </>
                ) : (
                  <>
                    <span>🧪</span>
                    <span>测试连接</span>
                  </>
                )}
              </button>
            ) : (
              <button
                onClick={saveConfig}
                className="flex-1 px-4 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-medium flex items-center justify-center gap-2"
                style={{ borderRadius: 'var(--radius-lg)' }}
              >
                <span>💾</span>
                <span>保存配置</span>
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}